package com.sunshine.util;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by WeiHong on 2016/12/2.
 */
public abstract class GetSqlSession {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetSqlSession.class);

    private static ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();

    public static SqlSession getSqlSession() {
        SqlSession sqlSession = tl.get();
        if (sqlSession == null) {
            sqlSession = GetSqlSessionFactory.getSqlSessionFactory().openSession();
            tl.set(sqlSession);
        }
        LOGGER.debug("sqlSession.hashCode():{}", sqlSession.hashCode());
        return sqlSession;
    }

    public static void commit() {
        if (tl.get() != null) {
            tl.get().commit();
            tl.get().close();
            tl.set(null);
            LOGGER.debug("sqlSession commit!");
        }
    }

    public static void rollback() {
        if (tl.get() != null) {
            tl.get().rollback();
            tl.get().close();
            tl.set(null);
            LOGGER.debug("sqlSession rollback!");
        }
    }
}
